package com.jumi.microservice.service.logistics.express;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jumi.microservice.common.utils.HttpClientUtils;
import com.jumi.microservice.common.utils.MD5;
import com.jumi.microservice.dto.logistics.Logistics;
import com.jumi.microservice.dto.logistics.LogisticsSearchRequest;
import com.jumi.microservice.dto.logistics.LogisticsSearchResponse;
import com.ymdd.api.sdk.util.Md5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author by mazhao
 * 中通快递
 * @Classname ZtoExpress
 * @Description TODO
 * @Date 2020/8/21 14:32
 */
@Component
public class ZtoExpress extends ResponseController implements Express {

    private static final Logger log = LoggerFactory.getLogger(ZtoExpress.class);

    @Resource
    HttpClientUtils httpClientUtils;

    private static String url = "https://japi.zto.com/traceInterfaceNewTraces";
    private static String companyId = "d2263cac977545ba905f3c9b5a13a639";
    private static String key = "7c9747bc628b";
    private static String msg_type = "NEW_TRACES";

    @Override
    public String expressCode() {
        return "ZTO";
    }

    @Override
    public LogisticsSearchResponse logisticsSearch(LogisticsSearchRequest request) throws NoSuchAlgorithmException {
        JSONArray jsonArray = null;
        log.info("中通快递查询参数[{}]", JSON.toJSONString(request));
        try {
            //组建数据格式
//            Map<String, String> parameters = new HashMap<>(3);
//            parameters.put("data", "['" + request.getLogisticsNo() + "']");
//            parameters.put("company_id", companyId);
//            parameters.put("msg_type", msg_type);
//            String strToDigest = paramsToQueryString(parameters) + key;
//            System.out.println(paramsToQueryString(parameters));
            String strToDigest = "data=['"+request.getLogisticsNo()+"']&company_id="+companyId+"&msg_type="+msg_type + key;
//            MessageDigest md = MessageDigest.getInstance("MD5");
//            md.update(strToDigest.getBytes(StandardCharsets.UTF_8));
//            String dataDigest = Base64Utils.encodeToString(md.digest());
            String dataDigest = Base64Utils.encodeToString(MD5.getInstance().hash(strToDigest));
//            String requestData = paramsToQueryStringUrlencoded(parameters);
//            System.out.println(requestData);
            String requestData = "data="+URLEncoder.encode("['"+request.getLogisticsNo()+"']", "UTF-8")+
                    "&company_id="+companyId+"&msg_type="+msg_type;
            //拼接请求头
            Map<String, String> headers = new HashMap<>(3);
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            headers.put("x-companyId", companyId);
            headers.put("x-dataDigest", dataDigest);
            //发送请求并接受返回
            String res = httpClientUtils.post(url, requestData, headers);
            //处理返回结果
            log.info("请求返回结果[{}]",res);
            JSONObject json = JSONObject.parseObject(res);
            jsonArray = json.getJSONArray("data").getJSONObject(0).getJSONArray("traces");
        } catch (Exception e) {
            log.error("中通快递查询出错[{}]", e.getMessage());
        }
        LogisticsSearchResponse logisticsSearchResponse = checkResult(jsonArray,request);
        return controller(logisticsSearchResponse,jsonArray,"desc","scanDate");
    }

//    public static String paramsToQueryString(Map<String, String> params) {
//        return params.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
//    }
//
//    public static String paramsToQueryStringUrlencoded(Map<String, String> params) {
//        return params.entrySet().stream().map(e -> {
//            try {
//                return e.getKey() + "=" + URLEncoder.encode(e.getValue(), "UTF-8");
//            } catch (UnsupportedEncodingException e1) {
//                return e.getValue();
//            }
//        }).collect(Collectors.joining("&"));
//    }
}
